# _*_ coding:utf-8_*_
"""
@Project:   appium
@FileName:  demo_location.py
@CreateDate:2023/3/15 22:24
@Author:    Jia
@Desc:  详解appium元素定位的几种方式，检查元素是否存在
"""

from common.emulator_desired import desired
from appium.webdriver.common.appiumby import AppiumBy
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from config import log

logger = log.log_execute('debug_logger')

driver = desired()

'''ID定位:    默认是AppiumBy.ID定位，可省略不写，resource-id也称为ID'''
driver.find_element("com.hle.lhzm:id/confirm_but").click()
driver.find_element("com.hle.lhzm:id/confirm_but").clear()
driver.find_element("com.hle.lhzm:id/confirm_but").send_keys('')

# 查找多个元素的属性值
ele = driver.find_elements("com.hle.lhzm:id/confirm_but")
for e in ele:
    print(e.get_attribute())

'''class name定位'''
driver.find_element(AppiumBy.CLASS_NAME, 'android.widget.RadioButton').send_keys('2018')
driver.find_element(AppiumBy.CLASS_NAME, 'android.widget.EditText').send_keys('zx2018')
driver.find_element(AppiumBy.CLASS_NAME, 'android.widget.Button').click()

'''AccessibilityId 定位,也称为content-desc'''
driver.find_element(AppiumBy.ACCESSIBILITY_ID, '我的').click()
driver.find_element(AppiumBy.ACCESSIBILITY_ID, '我的').clear()
driver.find_element(AppiumBy.ACCESSIBILITY_ID, '我的').send_keys('')

'''x-path 定位'''
# text
driver.find_element(AppiumBy.XPATH, '//[@text="请输入用户名"]').send_keys('zxw1234')
# contains 关键字
driver.find_element(AppiumBy.XPATH, '//android.widget.Button[contains(@text, "并继续")]')
# and 组合定位
driver.find_element(AppiumBy.XPATH, '//*[@class="android.widget.Button" and @text="同意并继续"]')
# 层级定位
driver.find_element(AppiumBy.XPATH, '//android.widget.RelativeLayout[1]/android.widget.Button[2]')

'''uiautomator 定位, 通过安卓自带的uiautomator查找'''
# text
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text("请输入用户名")').send_keys('zxw')
# text模糊定位
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text("请输入用")').send_keys('zxw')
# textStartsWith
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().textStartsWith("请输入")')
# textMatches 正则
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().resourceId("cn.com.open.mooc:id/et_phone_edit")')
# resourceIDMatches 定位
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().resourceIdMatches(".+et_phone_edit")')
# className
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().className("android.widget.EditText")')
# classNameMatches定位
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().classNameMatches (".*EditText")')
# 组合定位
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().resourceId("com.xueqiu.android:id/tab_name")'
                                                  '.text("我的")')
# 父子关系定位
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().resourceId("com.xueqiu.android:id/title_container")'
                                                  '.childSelector(text("股票"))')
# 兄弟关系定位
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().resourceId("com.xueqiu.android:id/title_container")'
                                                  '.fromParent(text("股票"))')
# 滚动查找
driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiScrollable(new UiSelector().scrollable(true).instance(0))'
                                                  '.scrollIntoView(new UiSelector().text("查找的元素文本").instance(0));')


'''跳转至其它层级，比如页面弹出的弹窗'''
driver.switch_to.context('WEBVIEW_com.wondershare.drfone')
driver.find_element('btn_send').click()

'''返回原来的层级'''
driver.switch_to.context('NATIVE_APP')
driver.find_element('android.widget.ImageButton').click()


def check_exist(driver, element):
    """
    检查元素是否存在
    :param driver: 驱动对象
    :param element: 以ID定位
    :return: 存在返回 true；失败返回 False
    """
    try:
        WebDriverWait(driver, 10).until(
            lambda x: x.find_element(By.ID, element), '没有找到%s' % element)
    except NoSuchElementException:
        return False
    else:
        return True


def click_element(driver, element, note=None):
    """
    显式等待10秒，元素出现则点击，不出现则输出控件名
    :param driver: 驱动实例对象
    :param element: ID定位元素
    :param note: 备注控件的名称
    :return: 出现则点击
    """
    try:
        element = WebDriverWait(driver, 10).until(
            lambda x: x.find_element(By.ID, element))
    except NoSuchElementException:
        logger.debug('no such element,没有出现%s' % note)
    except TimeoutException:
        logger.debug('time out,没有出现%s' % note)
    else:
        element.click()